package com.weiaibenpao.demo.chislim.ui;

import android.Manifest;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.database.ContentObserver;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.widget.Toast;

import com.weiaibenpao.demo.chislim.R;
import com.weiaibenpao.demo.chislim.RunningPreferences;
import com.weiaibenpao.demo.chislim.hurui.activity.HBaseActivity;
import com.weiaibenpao.demo.chislim.util.SystemUtil;
import com.weiaibenpao.demo.chislim.util.Utils;

/**
 * Created by ZJL on 2017/10/23.
 * 跑步公用逻辑可以放到这个BaseRunningActivity里来，具体的UI交互则仍由具体界面负责
 * 例如：
 * 状态栏的颜色设置（各跑步界面状态栏都一样，但与其他界面不一样）
 * setWindowFlag
 * mapView生命周期方法
 * 统一的跑步布局
 * 倒计时
 */

public  class BaseRunningActivity extends HBaseActivity {
    private final ContentObserver mGpsMonitor = new ContentObserver(null) {
        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            final boolean isEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
//            Log.e("BaseRunningActivity", "gps ： " + isEnabled+"\n current thread is "+Thread.currentThread());
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    onGPSStateChanged(isEnabled);
                }
            });
        }
    };

    private LocationManager mLocationManager;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        checkPermission();
        Utils.setMinimumAudioVolume(0.8f);//咕咚语音音量的做法是在首次进入跑步界面设置一个比较高的音量  并且注册监听音量变化并保存到本地，以后每次进入跑步界面从本地拿出来设置作为跑步界面音量
        if(RunningPreferences.getInstance().getIsShowWhiteListNotice()){
            showWhiteListNotice();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        getContentResolver().registerContentObserver(Settings.Secure.getUriFor(Settings.Secure.LOCATION_PROVIDERS_ALLOWED), false, mGpsMonitor);
    }

//    @Override
//    protected void onPause() {
//        super.onPause();
//        getContentResolver().unregisterContentObserver(mGpsMonitor);
//    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        getContentResolver().unregisterContentObserver(mGpsMonitor);
    }

    public void onGPSStateChanged(boolean isEnabled){

    }

    public boolean goEnableGPS() {
        if(!Utils.isGPSEnabled(this)){
            Utils.enableGPS(this);
            Toast.makeText(this,getString(R.string.gps_enable_notice),Toast.LENGTH_LONG).show();
            return true;
        }
        return false;
    }


    private int REQUEST_FINE_LOCATION_CODE = 100;

    private boolean checkPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    REQUEST_FINE_LOCATION_CODE);//自定义的code
            return false;
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (REQUEST_FINE_LOCATION_CODE == requestCode) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED){
                Toast.makeText(this,getString(R.string.please_enable_gps),Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void showWhiteListNotice(){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(getString(R.string.notice));
        String message ;
        if(SystemUtil.getSystemModel().contains(SystemUtil.MODEL_OPPO)){
            message = getString(R.string.oppo_white_list_notice);
        }else {
            message = getString(R.string.white_list_notice);
        }
        builder.setMessage(message);
        builder.setNegativeButton(getString(R.string.not_notify), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                RunningPreferences.getInstance().setIsShowWhiteListNotice(false);
            }
        });
        builder.setPositiveButton(getString(R.string.get_it), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });
        builder.setCancelable(true);
        builder.show();
    }

    public void showAddToWhiteListNotice(){
        if(RunningPreferences.getInstance().getIsShowWhiteListNotice()){
            return;//避免两种提示Dialog都弹出
        }
        if(RunningPreferences.getInstance().getIsShowAddToWhiteListNotice()){
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(getString(R.string.notice));
            String message ;
            if(SystemUtil.getSystemModel().contains(SystemUtil.MODEL_OPPO)){
                message = getString(R.string.oppo_app_killed_notice);
            }else {
                message = getString(R.string.app_killed_notice);
            }
            builder.setMessage(message);
            builder.setNegativeButton(getString(R.string.not_notify), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    RunningPreferences.getInstance().setIsShowAddToWhiteListNotice(false);
                }
            });
            builder.setPositiveButton(getString(R.string.get_it), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {

                }
            });
            builder.setCancelable(true);
            builder.show();
        }
    }

}
